﻿using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Model.Dao;
using Service.Util;
using SqlSugar;
using System.Text;

namespace RCWebApplication.CfgFile
{
    public static class HostBuildExtend
    {
        public static void Register(this WebApplicationBuilder app)
        {
            app.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            app.Host.ConfigureContainer<ContainerBuilder>(builder =>
            {
                builder.RegisterModule(new AutofactModuleRegister());
                app.Services.AddAutoMapper(typeof(AutoMapperConfigs));
            });
            app.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                //取出私钥
                var secretByte = Encoding.UTF8.GetBytes(app.Configuration["Authentication:SecretKey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = app.Configuration["Authentication:Issuer"],
                    //验证接收者
                    ValidateAudience = true,
                    ValidAudience = app.Configuration["Authentication:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });

            app.Services.AddSingleton<UserDao>();
            app.Services.AddSingleton <LoginInfoDao>();
            app.Services.AddScoped<SymmetrySecret>();
            app.Services.AddScoped<HostHolder>();
        }
    }
}
